import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { DictContext } from '../../../context/context';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';
import { Link } from 'react-router-dom';
import { cleanDict } from '../../../store/actions/dict';

import { listType, addType, updateType, delType, getType, refreshCache } from '../../../api/dict/type';
import { useStore } from 'react-redux';

function Dict() {
    const { useDict, addDateRange} = useContext(DictContext);
    const store = useStore();
    const { sys_normal_disable } = useDict('sys_normal_disable');
    const { RangePicker } = DatePicker;
    const [single, setSingle] = useState(true);
    const [multiple, setMultiple] = useState(true);
    const [ids, setIds] = useState([]);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [total, setTotal] = useState(0);
    const [open, setOpen] = useState(false);
    const [searchForm] = Form.useForm();
    const [formAdd] = Form.useForm();
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [queryParams, setQueryParams] = useState({
        pageNum: 1,
        pageSize: 5,
        dictName: undefined,
        dictType: undefined,
        status: undefined,
    });
    const [title, setTitle] = useState('');

    const columns =[
        {
            title: '字典编号',
            dataIndex: 'dictId',
            key: 'dictId',
            align: 'center',
        },
        {
            title: '字典名称',
            dataIndex: 'dictName',
            key: 'dictName',
            align: 'center',
        },
        {
            title: '字典类型',
            dataIndex: 'dictType',
            key: 'dictType',
            align: 'center',
            render: (text, record) => <Link to={`/system/dict-data/index/${record.dictId}`}>{text}</Link>
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (text, record) => <DictTag type="sys_normal_disable" value={text} options={sys_normal_disable} />
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
                <Popconfirm
                    title="删除确认"
                    description={`是否确认删除岗位编号为 ${record.dictId} 的数据项？`}
                    onConfirm={() => handleDelete(record)}
                    onCancel={delCancel}
                    okText="确定"
                    cancelText="取消"
                >
                <Button type='link'>删除</Button>
                </Popconfirm>
                </Space>
            ),
        }
    ];
    const onSelectChange = newSelectedRowKeys => {
        //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
        setSingle(newSelectedRowKeys.length != 1) ;
        setMultiple(!newSelectedRowKeys.length);
        setIds(newSelectedRowKeys);
      };
      const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
      };

      useEffect(() => {
        getListType();
      },[queryParams]);
      function getListType() {
        setLoading(true);
        listType(addDateRange(queryParams, queryParams.timeRange)).then(response => {
            setData(response.rows);
            setTotal(response.total);
            setLoading(false);
        });
      }

      const handleDelete = (record) => {
        const dictId = record?.dictId || ids;
        delType(dictId).then(response => {
            if (response.code === 200) {
                message.success('删除成功');
                getListType();
            } else {
                message.error(response.msg);
            }
        });
      }

      const handleUpdate = (record) => {
        formAdd.resetFields();
        const dictId = record?.dictId || ids;
        getType(dictId).then(response => {
            if (response.code === 200) {
                setOpen(true);
                setTitle('修改字典类型');
                formAdd.setFieldsValue(response.data);
            } else {
                message.error(response.msg);
            }
        });
      }

      const onChange = (pagination, filters, sorter) => {
        setQueryParams({
          ...queryParams,
          pageNum: pagination.current,
          pageSize: pagination.pageSize,
        });
      };


      const delCancel = () => {
        //message.info('取消删除');
      }

      const handleSearch = (values) => {
        setQueryParams( preState => ({
            ...preState,
            ...values,
          }));
      }

      const handleReset = () => {
        searchForm.resetFields();
      }

      const handleAdd = () => {
        setOpen(true);
        setTitle('新增字典类型');
      }

      const handleOk = () => {
            formAdd.validateFields().then(values => {
                if(formAdd.getFieldValue().dictId === undefined) {
                    addType(formAdd.getFieldValue()).then(response => {
                        if (response.code === 200) {
                            message.success('新增成功');
                            setOpen(false);
                            getListType();
                        }   
                });
                } else {
                    updateType(formAdd.getFieldValue()).then(response => {
                        if (response.code === 200) {
                            message.success('修改成功');
                            setOpen(false);
                            getListType();
                        } else {
                            message.error(response.msg);
                        }
                    });
            }
        })
      }

      const handleRefresh = () => {
          refreshCache().then(response => {
            //console.log('=====res=====',response, cleanDict());
            //store.dispatch(cleanDict);
            store.dispatch(cleanDict());
            message.success('刷新成功');
          })
      }
  return (
    <div>
        <Row gutter={[16, 16]}  style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
                <Form form={searchForm} layout="inline" onFinish={handleSearch}>
                    <Form.Item label="字典名称" name="dictName">
                        <Input placeholder="请输入字典名称"  allowClear/>
                    </Form.Item>
                    <Form.Item label="字典类型" name="dictType">
                        <Input placeholder="请输入字典类型"  allowClear />
                    </Form.Item>
                    <Form.Item label="状态" name="status" style={{width: '10%'}}>
                        <Select placeholder="请选择状态" options={sys_normal_disable.value} allowClear/>
                    </Form.Item>
                    <Form.Item label="创建时间" name="timeRange" style={{marginBottom: 16,}}>
                        <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"   allowClear/>
                    </Form.Item>
                    <Form.Item>
                        <Space>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
                        <Button type="default" icon={<RedoOutlined />}  onClick={ handleReset }>重置</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Col>
        </Row>
        <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
            <Space>
                <Button type="primary" icon={<PlusOutlined />}  onClick={() => handleAdd()}>新增</Button>
                <Button type="default" icon={<EditOutlined />} disabled={single} onClick={() => handleUpdate()}>修改</Button>
                <Button type="default" icon={<DeleteOutlined />} disabled={multiple} onClick={() => handleDelete()}>删除</Button>
                <Button type="default" icon={<SyncOutlined />} onClick={() => handleRefresh()}>刷新</Button>
                </Space>
            </Col>
        </Row>
        <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
            <Table loading={loading} rowSelection={rowSelection} dataSource={data} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.dictId} onChange={onChange}/>
            </Col>
        </Row>
        <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
            <Modal open={open} title={title} onCancel={() => setOpen(false)} onOk={handleOk}>
                <Form form={formAdd} layout="inline">
                    <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
                        <Col span={24}>
                    <Form.Item label="字典名称" name="dictName" rules={[{ required: true, message: '请输入字典名称' }]}>
                        <Input placeholder="请输入字典名称" />
                    </Form.Item>
                    </Col>
                    </Row>
                    <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
                        <Col span={24}>
                    <Form.Item label="字典类型" name="dictType" rules={[{ required: true, message: '请输入字典类型' }]}>
                        <Input placeholder="请输入字典类型" />
                    </Form.Item>
                    </Col>
                    </Row>
                    <Row gutter={[16, 16]} style={{marginBottom: '10px', width: '100%'}}>
                        <Col span={24}>
                    <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
                        <Radio.Group options={sys_normal_disable.value} />
                    </Form.Item>
                    </Col>
                    </Row>
                    <Row gutter={[16, 16]} style={{width: '100%'}}>
                        <Col span={24}>
                    <Form.Item label="备注" name="remark">
                        <Input.TextArea placeholder="请输入备注" />
                    </Form.Item>
                    </Col>
                    </Row>

                </Form>
            </Modal>

            </Col>
        </Row>
    </div>
  );
}

export default Dict;